package com.htjc.integral.account.service.impl;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.account.mapper.newdb.EcBpAccountIntegralDetailMapper;
import com.htjc.integral.account.mapper.newdb.EcBpAccountIntegralMapper;
import com.htjc.integral.account.mapper.newdb.EcBpConsNoIntegralMapper;
import com.htjc.integral.account.mapper.newdb.EcBpFrozenLockRecordMapper;
import com.htjc.integral.account.mapper.newdb.EcBpIncomeIntegralDetailMapper;
import com.htjc.integral.account.mapper.newdb.EcBpIncomeIntegralMapper;
import com.htjc.integral.account.mapper.olddb.EcBpMemberMapper;
import com.htjc.integral.account.service.INewAccountService;
import com.htjc.integral.account.util.AtbashUtils;
import com.htjc.integral.account.util.DebAsetHttpUtil;
import com.htjc.integral.account.util.DebUserCentreUtil;
import com.htjc.integral.account.util.ResultModel;
import com.htjc.integral.account.util.UrlConfigUtil;
import com.htjc.integral.account.util.enums.AccountConstant;
import com.htjc.integral.account.util.enums.NewAccountConstant;
import com.htjc.integral.account.util.enums.ProvinceCodeEnums;
import com.htjc.integral.account.util.enums.RedisKey;
import com.htjc.integral.common.util.PageUtil;
import com.htjc.integral.common.util.RequestUtils;
import com.htjc.integral.common.util.StringUtil;
import com.htjc.integral.common.util.TimeUtil;
import com.htjc.integral.common.util.UUIDUtil;
import com.htjc.integral.model.newaccount.EcBpAccountIntegral;
import com.htjc.integral.model.newaccount.EcBpAccountIntegralDetail;
import com.htjc.integral.model.newaccount.EcBpConsNoIntegral;
import com.htjc.integral.model.newaccount.EcBpFrozenLockRecord;
import com.htjc.integral.model.newaccount.EcBpInComeIntegral;
import com.htjc.integral.model.newaccount.EcBpInComeIntegralDetail;
import com.htjc.integral.model.newaccount.EcBpMemberOld;

import lombok.extern.slf4j.Slf4j;

/**
 * 账户中心的业务层实现类
 * @author hlc
 *
 */
@Slf4j(topic = "jfLog")
@Service
public class NewAccountServiceImpl implements INewAccountService{

	/** 积分账户总表  */
	@Autowired
	private EcBpAccountIntegralMapper accountIntegralMapper;

	/** 积分账户明细表  */
	@Autowired
	private EcBpAccountIntegralDetailMapper accountIntegralDetailMapper;

	/** 老系统积分明细表  */
	@Autowired
	private EcBpMemberMapper memberMapper;

	/** 积分收入表  */
	@Autowired
	private EcBpIncomeIntegralMapper incomeIntegralMapper;

	/** 积分户号账户表  */
	@Autowired
	private EcBpConsNoIntegralMapper consNoIntegralMapper;

	/** 积分冻结锁定记录表  */
	@Autowired
	private EcBpFrozenLockRecordMapper frozenLockRecordMapper;

	/** 积分收入消费明细表  */
	@Autowired
	private EcBpIncomeIntegralDetailMapper incomeIntegralDetailMapper;

	@Autowired
	private UrlConfigUtil urlConfigUtil;

	@Value("${spring.param.proportion}")
	private BigDecimal proportion;

	/**
	 * 积分划转/缴费积分划转
	 * @param jsonObject
	 * @return
	 * @throws Exception 
	 */
	@Transactional(rollbackFor=Exception.class)
	public JSONObject changeIntegral(JSONObject jsonObject,String flag) throws Exception{
		String logMsg=jsonObject.getString("LOG_MSG");
		JSONObject resultJson=new JSONObject();
		jsonObject.put("BUSS_TYPE", NewAccountConstant.BUSS_TYPE_DLJFZR);
		String serialNo=jsonObject.getString("BUSINESS_ID");//业务ID=流水号=支出ID=收支流水号
		String accountId=jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String accountName = jsonObject.getString("ACCOUNT_NAME");//账户名称
		BigDecimal deductionNum=jsonObject.getBigDecimal("DEDUCTION_NUM");//抵扣积分
		String acctDate=jsonObject.getString("ACCT_DATE");//账务日期
		String channelNo=jsonObject.getString("CHANNEL_NO");//渠道编码
		JSONArray userArray = jsonObject.getJSONArray("POWER_USER_LIST");//需要划转积分的户号list
		//查询账户积分总表,若无,需调用 积分账户新增接口
		EcBpAccountIntegral accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
		//如果积分账户总表中无该accountId,则新建该accountId账户
		if(accountIntegral==null){
			try {
				accountIntegral = addIntegralAccount(jsonObject,logMsg);
				//加锁
				accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
			}catch (Exception e) {
				log.error(logMsg+"新建账户异常");
				throw new Exception();
			}
		}
		if(deductionNum!=null&&deductionNum!=BigDecimal.ZERO){
			//调用扣减接口,扣减抵扣金额
			JSONObject reqJson=new JSONObject();
			reqJson.put("ACCOUNT_NAME", accountName);//账户名称
			reqJson.put("ACCOUNT_ID", accountId);//登录账户ID
			reqJson.put("BUSINESS_ID", serialNo);//业务ID=流水号=支出ID=收支流水号
			reqJson.put("INTEGRAL", deductionNum);//抵扣积分
			reqJson.put("DEAL_TIME", jsonObject.getString("DEAL_TIME"));//交易时间 YYYYMMddHHmmssSSS
			reqJson.put("BUSS_DISCRIBLE", NewAccountConstant.BUSS_TYPE_MAP.get(NewAccountConstant.BUSS_TYPE_JFJFDK));//业务描述、备注
			reqJson.put("CHANNEL_NO",channelNo);//业务描述、备注
			reqJson.put("BUSS_TYPE", NewAccountConstant.BUSS_TYPE_JFJFDK);//业务类型-缴费抵扣积分
			reqJson.put("LOG_MSG", jsonObject.getString("LOG_MSG")+"【抵扣积分扣减】");
			JSONObject retJson = deductionIntegral(reqJson,false);//false,不同步至资产中心
			if("-1".equals(retJson.getString("rcode"))){//扣减失败
				resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
				resultJson.put("DESCRIBE", "抵扣积分扣减失败");
				log.error(logMsg+"抵扣积分{}扣减失败",deductionNum);
				return ResultModel.ReturnErrorJson(resultJson);
			}
			JSONObject content = retJson.getJSONObject("content");
			resultJson.put("DEDUCTION_ID", content.getString("BUSINESS_ID"));
			log.info(logMsg+"抵扣积分{}扣减成功",deductionNum);
		}
		//根据前置传过来的list获取需要划转积分的户号列表
		List<Map<String, Object>> consNoList=new ArrayList<Map<String, Object>>();
		ProvinceCodeEnums[] enums = ProvinceCodeEnums.values();
		for (int i = 0; i < userArray.size(); i++) {
			Map<String, Object> map=new HashMap<String, Object>();
			String consNo = userArray.getJSONObject(i).getString("POWER_USER_NO");// 户号
			String orgNo =userArray.getJSONObject(i).getString("ORG_NO");// 供电单位编号
			String provinceCode = userArray.getJSONObject(i).getString("PROVINCE_CODE");// 网省编号
			BigDecimal payNum = userArray.getJSONObject(i).getBigDecimal("PAY_NUM");// 交费金额
			map.put("consNo", consNo);
			map.put("orgNo", orgNo);
			map.put("provinceCode", provinceCode);
			map.put("total", "01".equals(flag)?0:payNum.multiply(proportion));//如全部转换，该处填写0，否则填写相应积分值
			for (ProvinceCodeEnums ProvinceCodeEnum : enums) {
				if(provinceCode.equals(ProvinceCodeEnum.getLongCode())) {
					map.put("provinceCode", ProvinceCodeEnum.getShortCode());
				}
			}
			consNoList.add(map);
		}
		//查询强隔离穿透通道接口地址
		String invokeUrl=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_OUT_INVOKEQUERY.getKey());
		if (StringUtil.isNull(invokeUrl)) {
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", "获取强隔离穿透通道接口地址失败");
			log.error(logMsg+"配置强隔离穿透通道接口地址为空");
			return ResultModel.ReturnErrorJson(resultJson);
		}
		//查询内网接口地址
		String queryUrl=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_INTEGRAL_TRANSFER.getKey());
		if (StringUtil.isNull(queryUrl)) {
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", "获取内网户号积分划转地址失败");
			log.error(logMsg+"配置内网户号积分划转接口地址为空");
			return ResultModel.ReturnErrorJson(resultJson);
		}
		log.info(logMsg+"【户号中心划转】URL:" + queryUrl);
		//调用内网接口获取 各户号对应的积分
		JSONObject json=new JSONObject();
		json.put("userId", accountId);
		json.put("acctDate", acctDate);
		json.put("isAll", flag);//01全部转换 02部分转换
		json.put("businessId", serialNo);//业务ID
		json.put("data", consNoList);
		log.info(logMsg+"【户号中心划转】请求参数:" + json);
		JSONObject jsonReq=new JSONObject();
		jsonReq.put("wsdurl", queryUrl);
		jsonReq.put("data", json);
		long start = System.currentTimeMillis();//开始时间
		String result = RequestUtils.sendPost(invokeUrl, jsonReq.toString());
		long end = System.currentTimeMillis();//结束时间
		log.info(logMsg+"【户号中心划转】耗时："+(end-start)+"ms");
		log.info(logMsg+"【户号中心划转】返回参数:" + result);
		JSONObject balanceJson = JSONObject.parseObject(result);
		if ("-1".equals(balanceJson.getString("rcode"))) {
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", "户号中心划转失败");
			log.error(logMsg+"户号中心划转失败");
			return ResultModel.ReturnErrorJson(resultJson);
		}
		if ("2".equals(balanceJson.getString("rcode"))) {
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", "户号无积分可划转");
			log.error(logMsg+"户号无积分可划转");
			return ResultModel.ReturnSucceedJson(resultJson);
		}
		JSONArray data=balanceJson.getJSONArray("data");
		List<EcBpInComeIntegral> incomeIntegralList=new ArrayList<EcBpInComeIntegral>();//积分收入表List
		List<EcBpConsNoIntegral> consNoIntegralList=new ArrayList<EcBpConsNoIntegral>();//户号账户表List
		BigDecimal totalBalance=BigDecimal.ZERO;//本次转入的总转入积分
		for (int i=0;i<data.size();i++) {
			JSONObject infoJson = data.getJSONObject(i);
			String consNo=infoJson.getString("consNo");//户号
			BigDecimal balance=infoJson.getBigDecimal("total");//转换积分量
			Date calcTime = infoJson.getDate("calcTime");//积分生成时间
			String provinceCode=infoJson.getString("provinceCode");//省码
			totalBalance=totalBalance.add(balance);
			//遍历该户号下的积分明细
			//积分收入表
			EcBpInComeIntegral incomeIntegral=new EcBpInComeIntegral();
			incomeIntegral.setIncomeId(UUIDUtil.getUUID());//收入ID
			incomeIntegral.setAccountId(accountId);//总账户ID
			incomeIntegral.setConsNo(consNo);//户号
			incomeIntegral.setProvinceCode(provinceCode);//省码
			incomeIntegral.setOrgNo(infoJson.getString("orgNo"));//供电单位
			incomeIntegral.setPowerId(infoJson.getString("powerId"));//电力积分id
			incomeIntegral.setIncomeChannel(channelNo);//收入来源渠道编码
			incomeIntegral.setSerialNo(serialNo);//收入来源流水号,使用统一流水号
			incomeIntegral.setIncomeSource(NewAccountConstant.BUSS_TYPE_DLJFZR);//业务类型,04：积分划转
			incomeIntegral.setIncomeType(NewAccountConstant.OPERATION_TYPE_ZD);//收入类型,01自动
			incomeIntegral.setSourceInstructions(infoJson.getString("pointsType"));//来源说明/积分类型
			incomeIntegral.setSourceNumber(balance);//来源数量
			incomeIntegral.setIncomeBalance(balance);//收入总金额
			incomeIntegral.setUsableBalance(balance);//可用金额
			incomeIntegral.setChannelCreateTime(TimeUtil.getDateFomat(calcTime, "YYYYMMddHHmmss"));//渠道积分生成日期YYYYMMdd/交易时间
			incomeIntegral.setIncomeTime(TimeUtil.getDate("YYYYMMdd"));//收入日期YYYYMMdd
			String calcYearTime=TimeUtil.getDateFomat(calcTime, "YYYY");
			//针对河南2016年和2017年的积分，失效时间改为2020年12月31日23:59:59
			if("41101".equals(provinceCode)&&calcYearTime.equals("2016")){
				incomeIntegral.setStaleTime("20201231");//过期日期YYYYMMdd
			}else{
				incomeIntegral.setStaleTime((Integer.parseInt(TimeUtil.getDateFomat(calcTime, "YYYY"))+3)+"1231");//过期日期YYYYMMdd
			}
			incomeIntegral.setStatus(NewAccountConstant.INCOME_INTEGRAL_STATUS_USABLE);//状态01:可用
			incomeIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			incomeIntegralList.add(incomeIntegral);

			EcBpConsNoIntegral consNoIntegral=new EcBpConsNoIntegral();//户号账户实体
			consNoIntegral.setConsNo(consNo);//户号
			consNoIntegral.setAccountId(accountId);//总账户ID
			consNoIntegral.setProvinceCode(infoJson.getString("provinceCode"));//省码
			consNoIntegral.setCityCode(infoJson.getString("orgNo"));//地市编码
			consNoIntegral.setHsdwNo(infoJson.getString("orgNo"));//核算单位编码
			consNoIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			consNoIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//修改时间
			consNoIntegral.setBalance(balance);//积分余额
			for (int j = 0; j < consNoIntegralList.size(); j++) {
				EcBpConsNoIntegral ecBpConsNoIntegral = consNoIntegralList.get(j);
				if(consNo.equals(ecBpConsNoIntegral.getConsNo())){
					consNoIntegral.setBalance(consNoIntegral.getBalance().add(ecBpConsNoIntegral.getBalance()));
					consNoIntegralList.remove(j);//移除该条户号记录
				}
			}
			consNoIntegralList.add(consNoIntegral);
		}

		EcBpAccountIntegralDetail accountIntegralDetail = new EcBpAccountIntegralDetail();
		String detailId=UUIDUtil.getUUID();//明细ID（UUID）返回报文中的业务ID
		try {
			//插入积分收入表
			int incomeNum=incomeIntegralMapper.insertList(incomeIntegralList);
			log.info(logMsg+"积分收入表插入成功,条数:"+incomeNum);
			//插入户号账户表
			int consNoNum=consNoIntegralMapper.batchInsertOrUpdate(consNoIntegralList);
			log.info(logMsg+"积分户号账户表插入或更新成功,条数:"+consNoNum);
			//插入 积分明细表
			accountIntegralDetail.setDetailId(detailId);//明细ID（UUID）
			accountIntegralDetail.setAccountId(accountId);//总账户ID
			accountIntegralDetail.setAccountName(accountName);//账户名称
			accountIntegralDetail.setSerialNo(serialNo);//收支流水号
			accountIntegralDetail.setDealType(NewAccountConstant.DEAL_TYPE_INCOME);//业务方向
			accountIntegralDetail.setBalance(totalBalance);//积分金额
			accountIntegralDetail.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			accountIntegralDetail.setDealTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//交易时间=创建时间
			accountIntegralDetail.setBussDiscrible("01".equals(flag)?"积分划转":"缴费积分划转");//业务描述
			accountIntegralDetail.setBussType(NewAccountConstant.BUSS_TYPE_DLJFZR);//业务类型 04:积分划转
			accountIntegralDetail.setAcctDate(acctDate);//账务日期
			accountIntegralDetail.setChannelNo(channelNo);//渠道编码
			accountIntegralDetailMapper.insert(accountIntegralDetail);
			log.info(logMsg+"积分账户明细表插入成功,收支流水号:"+serialNo+",交易积分:"+totalBalance+",业务方向:"+NewAccountConstant.DEAL_TYPE_INCOME);
			//更新 积分账户总表
			accountIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
			accountIntegral.setBalance(accountIntegral.getBalance().add(totalBalance));//总可用积分
			accountIntegralMapper.update(accountIntegral);
			log.info(logMsg+"积分账户总表更新成功,总可用积分:"+accountIntegral.getBalance());
		} catch (Exception e) {
			log.error(logMsg+"数据库插入或更新失败"+e.getMessage());
			throw new Exception(e);
		}
		resultJson.put("BUSINESS_ID", detailId);
		resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
		resultJson.put("DESCRIBE", "积分划转成功");
		resultJson.put("BALANCE", accountIntegral.getBalance().toString());//可用余额
		
		jsonObject.put("INTEGRAL", totalBalance);
		JSONObject resultJS = modifyIntegral(jsonObject,NewAccountConstant.DEAL_TYPE_INCOME,logMsg);
		accountIntegralDetail.setStatus(resultJS.getString("resultCode"));//同步至资产中心状态（0:失败1:成功）
		accountIntegralDetailMapper.update(accountIntegralDetail);
		log.info(logMsg+"积分账户明细表更新成功,流水号:"+serialNo+",同步状态:"+resultJS.getString("resultCode"));
		//如果资产中心失败，直接返回失败
		if(resultJS.getString("resultCode").equals(NewAccountConstant.RETURN_CODE_FAIL)){
			return ResultModel.ReturnErrorJson();
		}

		JSONObject resultJ = queryAssetIntegral(jsonObject,logMsg);
		//如果资产中心余额查询成功，则使用 资产中心的余额
		resultJson.put("BALANCE", resultJ.getString("BALANCE"));//可用余额

		List<Map<String, Object>> resultList=new ArrayList<Map<String, Object>>();
		Map<String, Object> resMap=new HashMap<String, Object>();
		for (EcBpConsNoIntegral consNoIntegral : consNoIntegralList) {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("POWER_USER_NO", consNoIntegral.getConsNo());//户号
			map.put("INTEGRAL", consNoIntegral.getBalance().toString());//划转积分
			resultList.add(map);
			resMap.put(consNoIntegral.getConsNo(), consNoIntegral.getBalance());
		}
		//若有户号划转积分为0，需补充进返回报文list中
		if(consNoList.size()!=resultList.size()){
			for (Map<String, Object> map : consNoList) {
				if(resMap.get(map.get("consNo"))==null){
					Map<String, Object> map1=new HashMap<String, Object>();
					map1.put("POWER_USER_NO", map.get("consNo"));//户号
					map1.put("INTEGRAL", "0");//划转积分0
					resultList.add(map1);
				}
			}
		}
		resultJson.put("POWER_USER_LIST", resultList);
		//返回还需添加
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 积分余额查询
	 * @param jsonObject
	 * @return
	 * @throws Exception 
	 */
	@Transactional(rollbackFor=Exception.class)
	public JSONObject queryIntegral(JSONObject jsonObject) throws Exception{
		String logMsg=jsonObject.getString("LOG_MSG");
		//1.查询账户积分总表,若无,需调用 积分账户新增接口
		JSONObject resultJson=new JSONObject();
		String accountName = jsonObject.getString("ACCOUNT_NAME");//账户名称
		String accountId = jsonObject.getString("ACCOUNT_ID");//登录账户ID
		EcBpAccountIntegral accountIntegral = accountIntegralMapper.selectIntegralByAccountId(accountId);
		//如果积分账户总表中无该accountId,则新建该accountId账户
		if(accountIntegral==null){
			try {
				accountIntegral = addIntegralAccount(jsonObject,logMsg);
			}catch (Exception e) {
				log.error(logMsg+"新建账户异常");
				throw new Exception();
			}
		}

		JSONObject resultJ = queryAssetIntegral(jsonObject,logMsg);
		//如果资产中心余额查询成功，则使用 资产中心的余额
		resultJson.put("BALANCE", resultJ.getString("BALANCE"));//可用余额
		resultJson.put("TOTAL_BALANCE", resultJ.getString("TOTAL_BALANCE"));//积分余额

//		resultJson.put("BALANCE", accountIntegral.getBalance().toString());//可用余额
//		resultJson.put("TOTAL_BALANCE", accountIntegral.getTotalBalance().toString());//积分余额
		resultJson.put("ACCOUNT_NAME", accountName);//账户名称
		resultJson.put("ACCOUNT_ID", accountId);//登录账户ID
		resultJson.put("ACCOUNT_STATUS", accountIntegral.getStatus());//账户状态
		resultJson.put("CONSUMER_STATUS", accountIntegral.getConsType());//客户类型
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 积分明细查询
	 * @param jsonObject
	 * @return
	 */
	public JSONObject queryIntegralDetail(JSONObject jsonObject){
		JSONObject resultJson=new JSONObject();
		String accountId = jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String pageIndex = jsonObject.getString("PAGE_INDEX");//页码
		String dealType = jsonObject.getString("AMT_DIRECTION");//业务方向
		String startDate = jsonObject.getString("START_DATE");//开始时间
		String endDate = jsonObject.getString("END_DATE");//结束时间
		String flag=jsonObject.getString("FLAG");//是否查询09：老系统积分转入  空不查，不空则查
		//分页
		PageUtil pageUtil=new PageUtil();
		pageUtil.setPageIndex(Integer.parseInt(pageIndex));//设置页码
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("accountId", accountId);//账户ID
		params.put("start", pageUtil.getStart());//分页起始位置
		params.put("end", pageUtil.getEnd());//分页结束位置
		params.put("dealType", dealType);//业务方向
		params.put("startDate", startDate);//开始时间
		params.put("endDate", endDate);//结束时间
		params.put("flag", flag);//是否查询09：老系统积分转入  空不查，不空则查
		//业务明细
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		resultList = accountIntegralDetailMapper.selectDetailByUnionId(params);
		//当业务类型为电力积分转入时，查询转入明细
		List<EcBpInComeIntegral> incomeIntegralList = incomeIntegralMapper.select04Detail(accountId);
		for (Map<String, Object> map : resultList) {
			if(map.get("BUSS_DISCRIBLE").equals(NewAccountConstant.BUSS_TYPE_DLJFZR)){
				List<Map<String, Object>> detailList = new ArrayList<Map<String, Object>>();
				for (EcBpInComeIntegral incomeIntegral : incomeIntegralList) {
					Map<String, Object> map1=new HashMap<String, Object>();
					if(incomeIntegral.getSerialNo().equals(map.get("SERIAL_NO").toString())){
						map1.put("CONS_NO", incomeIntegral.getConsNo());//户号
						map1.put("INTEGRAL", incomeIntegral.getIncomeBalance());//转入积分值
						map1.put("INTEGRAL_TYPE", incomeIntegral.getSourceInstructions());//积分类型
						detailList.add(map1);
					}
				}
				map.put("DETAIL_LIST", detailList);
			}
			map.put("BUSS_DISCRIBLE", NewAccountConstant.BUSS_TYPE_MAP.get(map.get("BUSS_DISCRIBLE")));
		}
		int totalCount = accountIntegralDetailMapper.selectTotalCount(params);
		pageUtil.setTotalCount(totalCount);//设置总条数,get总页数
		resultJson.put("RECNUM", resultList.size());//当前笔数
		resultJson.put("TOTRECNUM", totalCount);//总笔数
		resultJson.put("PAGCNT", pageUtil.getTotalPage());//总页数
		resultJson.put("RESULT_LIST", resultList);
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 积分余额增加
	 * @param jsonObject
	 * @return
	 * @throws Exception 
	 */
	@Transactional(rollbackFor=Exception.class)
	public JSONObject addIntegral(JSONObject jsonObject) throws Exception{
		String logMsg=jsonObject.getString("LOG_MSG");
		//1.查询账户积分总表,若无,需调用 积分账户新增接口
		JSONObject resultJson=new JSONObject();
		String accountName = jsonObject.getString("ACCOUNT_NAME");//账户名称
		String accountId = jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String serialNo=jsonObject.getString("BUSINESS_ID");//业务ID=流水号
		BigDecimal balance=jsonObject.getBigDecimal("INTEGRAL").setScale(0, BigDecimal.ROUND_DOWN);//收入积分
		String dealTime=jsonObject.getString("DEAL_TIME");//交易时间 YYYYMMddHHmmssSSS
		String acctDate=jsonObject.getString("ACCT_DATE");//账务日期YYYYMMdd
		//户号相关字段
		String consNo=jsonObject.getString("CONS_NO");//户号
		String hsdwNo=jsonObject.getString("HSDW_NO");//核算单位编码
		String provinceCode=jsonObject.getString("PROVINCE_CODE");//网省编码
		String cityCode=jsonObject.getString("CITY_CODE");//地市编码
		//若查询出数据，则加悲观锁，若无数据，则新建账户后，再次查询加悲观锁
		EcBpAccountIntegral accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
		//如果积分账户总表中无该accountId,则新建该accountId账户
		if(accountIntegral==null){
			try {
				accountIntegral = addIntegralAccount(jsonObject,logMsg);
				//加锁
				accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
			}catch (Exception e) {
				log.error(logMsg+"新建账户异常");
				throw new Exception();
			}
		}
		//账户积分明细表实体,异步同步资产中心时需要用到,所以写在try catch外面
		EcBpAccountIntegralDetail accountIntegralDetail = new EcBpAccountIntegralDetail();
		String detailId=UUIDUtil.getUUID();//明细ID（UUID）返回报文中的业务ID
		try {
			//2.插入积分收入表
			EcBpInComeIntegral incomeIntegral=new EcBpInComeIntegral();
			incomeIntegral.setIncomeId(UUIDUtil.getUUID());//收入ID
			incomeIntegral.setAccountId(accountId);//总账户ID
			incomeIntegral.setConsNo(null);//积分余额增加,户号为空
			incomeIntegral.setIncomeChannel(jsonObject.getString("CHANNEL_NO"));//收入来源渠道编码
			incomeIntegral.setSerialNo(serialNo);//收入来源流水号,使用统一流水号
			incomeIntegral.setIncomeSource(jsonObject.getString("BUSS_TYPE"));//收入来源=业务类型
			incomeIntegral.setIncomeType(jsonObject.getString("OPERATION_TYPE"));//操作类型,01:自动02:人工
			incomeIntegral.setSourceInstructions(jsonObject.getString("BUSS_DISCRIBLE"));//来源说明=业务描述
			incomeIntegral.setSourceNumber(balance);//来源数量
			incomeIntegral.setIncomeBalance(balance);//收入总金额
			incomeIntegral.setUsableBalance(balance);//可用金额
			incomeIntegral.setChannelCreateTime(jsonObject.getString("CREATE_DATE"));//渠道积分生成日期
			incomeIntegral.setIncomeTime(TimeUtil.getDate("YYYYMMdd"));//收入日期
			incomeIntegral.setStaleTime((Integer.parseInt(TimeUtil.getDate("YYYY"))+3)+"1231");//过期日期
			incomeIntegral.setStatus(NewAccountConstant.INCOME_INTEGRAL_STATUS_USABLE);//状态
			incomeIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			incomeIntegralMapper.insert(incomeIntegral);
			log.info(logMsg+"积分收入表插入成功");
			//3.插入账户积分明细表
			accountIntegralDetail.setDetailId(detailId);//明细ID（UUID）
			accountIntegralDetail.setAccountId(accountId);//总账户ID
			accountIntegralDetail.setAccountName(accountName);//账户名称
			accountIntegralDetail.setSerialNo(serialNo);//收支流水号
			accountIntegralDetail.setDealType(NewAccountConstant.DEAL_TYPE_INCOME);//业务方向
			accountIntegralDetail.setBalance(balance);//积分金额
			accountIntegralDetail.setDealTime(dealTime);//交易时间
			accountIntegralDetail.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			accountIntegralDetail.setBussDiscrible(jsonObject.getString("BUSS_DISCRIBLE"));//业务描述
			accountIntegralDetail.setBussType(jsonObject.getString("BUSS_TYPE"));//业务类型
			accountIntegralDetail.setAcctDate(acctDate);//账务日期
			accountIntegralDetail.setChannelNo(jsonObject.getString("CHANNEL_NO"));//渠道编码
			accountIntegralDetailMapper.insert(accountIntegralDetail);
			log.info(logMsg+"积分账户明细表插入成功,收支流水号:"+serialNo+",交易积分:"+balance+",业务方向:"+NewAccountConstant.DEAL_TYPE_INCOME);
			//4.判断户号是否为空,如果不为空,则插入或更新户号账户表(在sql中判断)
			if(!StringUtil.isNull(consNo)){
				EcBpConsNoIntegral consNoIntegral=new EcBpConsNoIntegral();
				consNoIntegral.setConsNo(consNo);//户号
				consNoIntegral.setAccountId(accountId);//总账户ID
				consNoIntegral.setHsdwNo(hsdwNo);//核算单位编码
				consNoIntegral.setProvinceCode(provinceCode);//网省编码
				consNoIntegral.setCityCode(cityCode);//地市编码
				consNoIntegral.setBalance(balance);//增加积分
				consNoIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
				consNoIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//更新时间
				consNoIntegralMapper.insertOrUpdate(consNoIntegral);
				log.info(logMsg+"积分户号账户表插入或更新成功,户号:"+consNo+",增加积分:"+balance);
			}
			//5.更新账户积分总表增加积分
			accountIntegral.setBalance(accountIntegral.getBalance().add(balance));//现有可用积分+收入积分
			accountIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//修改时间
			accountIntegralMapper.update(accountIntegral);
			log.info(logMsg+"积分账户总表更新成功,总可用积分:"+accountIntegral.getBalance());
		} catch (Exception e) {
			log.error(logMsg+"数据库更新或插入失败"+e);
			throw new Exception();
		}
		resultJson.put("BUSINESS_ID", detailId);
		resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
		resultJson.put("DESCRIBE", "积分增加成功");
		resultJson.put("BALANCE", accountIntegral.getBalance().toString());//可用余额

		//同步
		JSONObject resultJ = modifyIntegral(jsonObject,NewAccountConstant.DEAL_TYPE_INCOME,logMsg);
		accountIntegralDetail.setStatus(resultJ.getString("resultCode"));//同步至资产中心状态（0:失败1:成功）
		accountIntegralDetailMapper.update(accountIntegralDetail);
		log.info(logMsg+"积分账户明细表更新成功,流水号:"+serialNo+",同步状态:"+resultJ.getString("resultCode"));
		//如果资产中心失败，直接返回失败
		if(resultJ.getString("resultCode").equals(NewAccountConstant.RETURN_CODE_FAIL)){
			return ResultModel.ReturnErrorJson();
		}

		JSONObject result = queryAssetIntegral(jsonObject,logMsg);
		//如果资产中心余额查询成功，则使用 资产中心的余额
		resultJson.put("BALANCE", result.getString("BALANCE"));//可用余额
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 积分余额扣减
	 * @param jsonObject
	 * @return
	 * @throws Exception 
	 */
	@Transactional(rollbackFor=Exception.class)
	public JSONObject deductionIntegral(JSONObject jsonObject,boolean flag) throws Exception{
		String logMsg=jsonObject.getString("LOG_MSG");
		//1.查询账户积分总表,若无,需调用 积分账户新增接口
		String accountName = jsonObject.getString("ACCOUNT_NAME");//账户名称
		String accountId = jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String serialNo=jsonObject.getString("BUSINESS_ID");//业务ID=流水号=支出ID=收支流水号
		BigDecimal balance=jsonObject.getBigDecimal("INTEGRAL").setScale(0, BigDecimal.ROUND_DOWN);//扣减积分
		if(balance.compareTo(BigDecimal.ZERO)==-1){
			balance=balance.multiply(new BigDecimal(-1));
			jsonObject.put("INTEGRAL", balance);
		}
		String consNos=jsonObject.getString("CONS_NO");//指定的户号  123456789|123456787|....
		String dealTime=jsonObject.getString("DEAL_TIME");//交易时间 YYYYMMddHHmmssSSS
		String bussDiscrible=jsonObject.getString("BUSS_DISCRIBLE");//业务描述、备注
		String bussType=jsonObject.getString("BUSS_TYPE");//业务类型
		String acctDate=jsonObject.getString("ACCT_DATE");//账务日期

		JSONObject resultJson=new JSONObject();
		EcBpAccountIntegral accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
		//如果积分账户总表中无该accountId,则新建该accountId账户
		if(accountIntegral==null){
			try {
				accountIntegral = addIntegralAccount(jsonObject,logMsg);
				//加锁
				accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
			}catch (Exception e) {
				log.error(logMsg+"新建账户异常");
				throw new Exception();
			}
		}
		//1.查询账户积分总表获取可用积分,判断是否满足扣减条件
		if(balance.compareTo(accountIntegral.getBalance())==1){
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE","积分账户余额不足");
			log.info(logMsg+"积分账户余额不足,可用积分:"+accountIntegral.getBalance()+",扣减积分:"+balance);
			return ResultModel.ReturnErrorJson(resultJson);
		}
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("accountId", accountId);
		//如果户号不为空,则为指定户号扣减,添加查询条件
		if(!StringUtil.isNull(consNos)){
			String[] consNo = consNos.split("\\|");
			params.put("array", consNo);
		}
		//从积分收入表查询所有收入明细
		List<EcBpInComeIntegral> incomeIntegralList = incomeIntegralMapper.selectListByIdAndConsNo(params);
		if (incomeIntegralList==null||incomeIntegralList.size()==0) {
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE","积分账户余额不足");
			log.info(logMsg+"积分收入余额不足,扣减积分:"+balance);
			return ResultModel.ReturnErrorJson(resultJson);
		}
		//判断该扣减哪几条明细
		BigDecimal incomeExpendBalance=new BigDecimal("0");//收入表扣减的总积分
		List<EcBpInComeIntegral> needExpendList=new ArrayList<EcBpInComeIntegral>();//收入表 需要扣减积分的list
		List<EcBpInComeIntegralDetail> expendDetailList=new ArrayList<EcBpInComeIntegralDetail>();//收入消费明细表 需要添加的list
		List<EcBpConsNoIntegral> consNoList=new ArrayList<EcBpConsNoIntegral>();//户号账户表 需要更新的list
		String time=TimeUtil.getDate("YYYYMMddHHmmssSSS");
		for (EcBpInComeIntegral incomeIntegral : incomeIntegralList) {
			//积分收入表
			EcBpInComeIntegral needExpend=new EcBpInComeIntegral();
			needExpend.setIncomeId(incomeIntegral.getIncomeId());//收入ID
			needExpend.setUpdateTime(time);//修改时间
			//积分收入消费明细表
			EcBpInComeIntegralDetail expendDetail=new EcBpInComeIntegralDetail();
			expendDetail.setDetailId(UUIDUtil.getUUID());//收入消费明细ID
			expendDetail.setExpendId(serialNo);//业务ID=流水号=支出ID
			expendDetail.setTotalConsumeBalance(balance);//该笔支出总消费金额
			expendDetail.setIncomeId(incomeIntegral.getIncomeId());//收入ID
			expendDetail.setCreateTime(time);

			//户号账户表,判断户号是否为空
			EcBpConsNoIntegral consNoIntegral=new EcBpConsNoIntegral();
			String consNo=incomeIntegral.getConsNo();
			if(!StringUtil.isNull(consNo)){
				consNoIntegral.setConsNo(incomeIntegral.getConsNo());//户号
				consNoIntegral.setAccountId(accountId);//总账号ID
				consNoIntegral.setUpdateTime(time);//修改时间
			}

			incomeExpendBalance=incomeExpendBalance.add(incomeIntegral.getUsableBalance());
			if(incomeExpendBalance.compareTo(balance)==-1){//继续下一条收入记录
				needExpend.setUsableBalance(new BigDecimal("0"));//该条收入积分扣减为0
				needExpend.setStatus(NewAccountConstant.INCOME_INTEGRAL_STATUS_USEUP);//02已耗尽
				expendDetail.setIncomeConsumeBalance(incomeIntegral.getUsableBalance());//该条收入积分耗尽
				needExpendList.add(needExpend);
				expendDetailList.add(expendDetail);
				if(!StringUtil.isNull(consNo)){
					consNoIntegral.setBalance(incomeIntegral.getUsableBalance());
					for (int i = 0; i < consNoList.size(); i++) {
						EcBpConsNoIntegral ecBpConsNoIntegral = consNoList.get(i);
						if(consNo.equals(ecBpConsNoIntegral.getConsNo())){
							consNoIntegral.setBalance(consNoIntegral.getBalance().add(ecBpConsNoIntegral.getBalance()));
							consNoList.remove(i);//移除该条户号记录
						}
					}
					consNoList.add(consNoIntegral);
				}
				continue;
			}else if(incomeExpendBalance.compareTo(balance)==0){//刚好扣减完,跳出循环
				needExpend.setUsableBalance(new BigDecimal("0"));//该条收入积分扣减为0
				needExpend.setStatus(NewAccountConstant.INCOME_INTEGRAL_STATUS_USEUP);//02已耗尽
				expendDetail.setIncomeConsumeBalance(incomeIntegral.getUsableBalance());//该条收入积分耗尽
				needExpendList.add(needExpend);
				expendDetailList.add(expendDetail);
				if(!StringUtil.isNull(consNo)){
					consNoIntegral.setBalance(incomeIntegral.getUsableBalance());
					for (int i = 0; i < consNoList.size(); i++) {
						EcBpConsNoIntegral ecBpConsNoIntegral = consNoList.get(i);
						if(consNo.equals(ecBpConsNoIntegral.getConsNo())){
							consNoIntegral.setBalance(consNoIntegral.getBalance().add(ecBpConsNoIntegral.getBalance()));
							consNoList.remove(i);//移除该条户号记录
						}
					}
					consNoList.add(consNoIntegral);
				}
				break;
			}else if(incomeExpendBalance.compareTo(balance)==1){//扣减多了,跳出循环
				needExpend.setUsableBalance(incomeExpendBalance.subtract(balance));//计算该条记录剩余积分
				expendDetail.setIncomeConsumeBalance(incomeIntegral.getUsableBalance()
						.subtract(incomeExpendBalance.subtract(balance)));//该条收入扣减的积分
				consNoIntegral.setBalance(expendDetail.getIncomeConsumeBalance());
				if(!StringUtil.isNull(consNo)){
					for (int i = 0; i < consNoList.size(); i++) {
						EcBpConsNoIntegral ecBpConsNoIntegral = consNoList.get(i);
						if(consNo.equals(ecBpConsNoIntegral.getConsNo())){
							consNoIntegral.setBalance(consNoIntegral.getBalance().add(ecBpConsNoIntegral.getBalance()));
							consNoList.remove(i);//移除该条户号记录
						}
					}
					consNoList.add(consNoIntegral);
				}
				needExpendList.add(needExpend);
				expendDetailList.add(expendDetail);
				break;
			}
		}
		//账户积分明细表实体,异步同步资产中心时需要用到,所以写在try catch外面
		EcBpAccountIntegralDetail integralDetail=new EcBpAccountIntegralDetail();
		String detailId=UUIDUtil.getUUID();//明细ID（UUID）返回报文中的业务ID
		try {
			//更新收入表记录可用积分和状态
			incomeIntegralMapper.batchUpdate(needExpendList);
			log.info(logMsg+"积分收入表更新成功,共更新"+needExpendList.size()+"条数据");
			//插入积分收入消费明细表
			incomeIntegralDetailMapper.insertList(expendDetailList);
			log.info(logMsg+"积分收入消费明细表插入成功,共插入"+expendDetailList.size()+"条数据");
			//记录中有户号不为空的,扣减 户号账户表
			if(consNoList!=null&&consNoList.size()!=0){
				consNoIntegralMapper.batchUpdate(consNoList);
				log.info(logMsg+"积分户号账户表更新成功,共更新"+consNoList.size()+"条数据");
			}
			//插入积分账户明细表 扣减记录
			integralDetail.setDetailId(detailId);//明细ID（UUID）
			integralDetail.setAccountId(accountId);//总账户ID
			integralDetail.setAccountName(accountName);//账户名称
			integralDetail.setSerialNo(serialNo);//业务ID=流水号=支出ID=收支流水号
			integralDetail.setDealType(NewAccountConstant.DEAL_TYPE_EXPEND);//方向（0:出1:入）
			integralDetail.setBalance(balance);//积分金额
			integralDetail.setDealTime(dealTime);//交易时间
			integralDetail.setCreateTime(time);//创建时间
			integralDetail.setBussDiscrible(bussDiscrible);//业务描述
			integralDetail.setBussType(bussType);//业务类型
			integralDetail.setAcctDate(acctDate);//账务日期
			integralDetail.setChannelNo(jsonObject.getString("CHANNEL_NO"));//渠道编码
			accountIntegralDetailMapper.insert(integralDetail);
			log.info(logMsg+"积分账户明细表插入成功,收支流水号:"+serialNo+",交易积分:"+balance+",业务方向:"+NewAccountConstant.DEAL_TYPE_EXPEND);
			//更新账户积分总表扣减积分
			accountIntegral.setBalance(accountIntegral.getBalance().subtract(balance));
			accountIntegral.setUpdateTime(time);
			accountIntegralMapper.update(accountIntegral);
			log.info(logMsg+"积分账户总表更新成功,总可用积分:"+accountIntegral.getBalance());
		} catch (Exception e) {
			log.error(logMsg+"数据库更新或插入失败"+e.getMessage());
			throw new Exception(e);
		}
		resultJson.put("BUSINESS_ID", detailId);
		resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
		resultJson.put("DESCRIBE","积分余额扣减成功");
		resultJson.put("BALANCE", accountIntegral.getBalance().toString());//可用余额

		if(flag){
			JSONObject result = modifyIntegral(jsonObject,NewAccountConstant.DEAL_TYPE_EXPEND,logMsg);
			integralDetail.setStatus(result.getString("resultCode"));//同步至资产中心状态（0:失败1:成功）
			accountIntegralDetailMapper.update(integralDetail);
			log.info(logMsg+"积分账户明细表更新成功,流水号:"+serialNo+",同步状态:"+result.getString("resultCode"));
			//如果资产中心失败，直接返回失败
			if(result.getString("resultCode").equals(NewAccountConstant.RETURN_CODE_FAIL)){
				return ResultModel.ReturnErrorJson();
			}
			JSONObject resultJ = queryAssetIntegral(jsonObject,logMsg);
			//如果资产中心余额查询成功，则使用 资产中心的余额
			resultJson.put("BALANCE", resultJ.getString("BALANCE"));//可用余额
		}
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 积分账户新增
	 * @param jsonObject
	 * @return
	 * @throws Exception 
	 */
	@Transactional(rollbackFor=Exception.class)
	public EcBpAccountIntegral addIntegralAccount(JSONObject json,String logMs) throws Exception{
		String logMsg=json.getString("LOG_MSG")+"【积分账户新增】";
		String accountId=json.getString("ACCOUNT_ID");
		String accountName=json.getString("ACCOUNT_NAME");
		String bussId=json.getString("BUSINESS_ID");
		EcBpAccountIntegral accountIntegral=new EcBpAccountIntegral();//积分账户总表
		accountIntegral.setAccountName(accountName);
		accountIntegral.setAccountId(accountId);
		accountIntegral.setBalance(new BigDecimal("0"));//可用积分:默认为0
		accountIntegral.setFrozenBalance(new BigDecimal("0"));//冻结积分:默认为0
		accountIntegral.setLockBalance(new BigDecimal("0"));//锁定积分:默认为0
		accountIntegral.setStatus(NewAccountConstant.ACCOUNT_STATUS_NORMAL);//账户状态:默认为01正常
		accountIntegral.setConsType(NewAccountConstant.CONS_TYPE_GENERAL);//客户类型:默认为1一般用电客户
		//查询老系统所有积分收入明细
		List<EcBpMemberOld> oldIntegralList=null;
		try {
			oldIntegralList = memberMapper.selectOldIntegral(accountId);
		} catch (Exception e) {
			log.error(logMsg+"老系统数据库查询失败");
			throw new Exception();
		}
		//如果是空,直接新建积分为0的新账户
		if(oldIntegralList==null||oldIntegralList.size()==0){
			accountIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
			accountIntegralMapper.insert(accountIntegral);
			log.info(logMsg+"老系统无积分数据,新建账户accountId:"+accountId+",accountName:"+accountName);
			return accountIntegral;
		}else{
			return oldDbListToNewDb(oldIntegralList, accountIntegral, json.getString("CHANNEL_NO"), bussId, logMsg);
		}
	}

	/**
	 * 调用资产中心变更积分接口
	 * @param json
	 * @param flag
	 * @return
	 */
	public JSONObject modifyIntegral(JSONObject json,String flag,String logMsg){
		JSONObject resultJson=new JSONObject();
		//拼接请求参数
		//header头部
		Map<String, String> headerMap=new HashMap<String, String>();
		try {
			headerMap.put("IP",InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e1) {
			log.error(logMsg+"获取服务器IP失败");
			headerMap.put("IP","127.0.0.1");
		}
		String accountName=json.getString("ACCOUNT_NAME");//账户名称
		if(!StringUtil.isNull(accountName)){
			accountName=AtbashUtils.encrypt(accountName);//加密
		}
		headerMap.put("CHANNEL_RESOURCE",json.getString("CHANNEL_NO"));//渠道编码
		//data
		Map<String, String> dataMap=new HashMap<String, String>();
		dataMap.put("ASSET_TYPE", NewAccountConstant.ASSET_TYPE);//01充值卡02卡券03 积分
		dataMap.put("REQUEST_ID",json.getString("BUSINESS_ID"));
		dataMap.put("REQUEST_TIME", TimeUtil.getDate("YYYYMMddHHmmssSSS"));
		dataMap.put("UNIONID",json.getString("ACCOUNT_ID"));//账户ID
		dataMap.put("AMT_DIRECTION",flag);//业务方向
		dataMap.put("STATUS", "02");//默认02启用
		dataMap.put("USER_NAME",accountName);
		String acctDate=json.getString("ACCT_DATE");
		dataMap.put("ASS_DATE",StringUtil.isNull(acctDate)?TimeUtil.getDate("YYYYMMdd"):acctDate);//账务日期
		String resultMsg="";
		dataMap.put("BUSS_TYPE",json.getString("BUSS_TYPE")+NewAccountConstant.BUSS_TYPE_MAP.get(json.getString("BUSS_TYPE")));//业务类型+业务描述
		dataMap.put("INTEGRAL",json.getBigDecimal("INTEGRAL").setScale(0, BigDecimal.ROUND_DOWN)+"");//分值

		if(NewAccountConstant.DEAL_TYPE_INCOME.equals(flag)){
			resultMsg="积分增加成功";
		}else{
			resultMsg="积分扣减成功";
		}
		dataMap.put("SIGN_DATA", json.getString("ACCOUNT_ID")+"|"+NewAccountConstant.ASSET_TYPE+"|"+json.getString("CHANNEL_NO"));
		//获取接口地址
		String url=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ZCZX_INTEGRAL_ADD.getKey());
		if (StringUtil.isNull(url)) {
			log.error(logMsg+"配置资产中心接口为空");
			resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("resultMsg", "配置资产中心接口为空");
			return resultJson;
		}
		//调用资产中心
		try {
			JSONObject result = JSONObject.parseObject(DebAsetHttpUtil.sendPost(url,headerMap, dataMap,logMsg));

			JSONObject resHeader=result.getJSONObject("header");
			JSONObject resData=result.getJSONObject("data");
			if(AccountConstant.REPCD_SUCCESS.equals(resHeader.getString("repcd"))
					&&AccountConstant.RESULT_CODE_SUCCESS.equals(resData.getString("RESULT_CODE"))){
				log.info(logMsg+"资产中心处理成功,交易积分:"+json.getBigDecimal("INTEGRAL").setScale(0, BigDecimal.ROUND_DOWN));
				resultJson.put("resultCode",NewAccountConstant.RETURN_CODE_SUCCESS);
				resultJson.put("resultMsg", resultMsg);
			}else{
				String msg=AccountConstant.REPCD_SUCCESS.equals(resHeader.getString("repcd"))?resData.getString("RESULT_MESSAGE"):resHeader.getString("repmsg");
				resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
				log.info(logMsg+"资产中心处理失败:"+msg);
				resultJson.put("resultMsg", msg);
			}
			return resultJson;
		} catch (Exception e) {
			log.info(logMsg+"资产中心接口处理异常:"+e.getMessage());
			resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("resultMsg", "资产中心接口异常");
			return resultJson;
		}
	}

	/**
	 * 调用资产中心查询余额接口
	 * @param json
	 * @return
	 */
	public JSONObject queryAssetIntegral(JSONObject json,String logMsg){
		JSONObject resultJson=new JSONObject();
		resultJson.put("BALANCE",BigDecimal.ZERO);//可用余额
		resultJson.put("TOTAL_BALANCE", BigDecimal.ZERO);//积分余额
		//拼接请求参数
		//header头部
		Map<String, String> headerMap=new HashMap<String, String>();
		try {
			headerMap.put("IP",InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e1) {
			log.error(logMsg+"获取服务器IP失败");
			headerMap.put("IP","127.0.0.1");
		}
		String accountName=json.getString("ACCOUNT_NAME");//账户名称
		if(!StringUtil.isNull(accountName)){
			accountName=AtbashUtils.encrypt(accountName);//加密
		}
		headerMap.put("CHANNEL_RESOURCE",json.getString("CHANNEL_NO"));//渠道编码
		//data
		Map<String, String> dataMap=new HashMap<String, String>();
		dataMap.put("ASSET_TYPE", NewAccountConstant.ASSET_TYPE);//01充值卡02卡券03 积分
		dataMap.put("REQUEST_ID", StringUtil.isNull(json.getString("BUSINESS_ID"))
				?UUIDUtil.getUUID():json.getString("BUSINESS_ID"));
		dataMap.put("REQUEST_TIME", TimeUtil.getDate("YYYYMMddHHmmssSSS"));
		dataMap.put("UNIONID",json.getString("ACCOUNT_ID"));//账户ID
		dataMap.put("USER_NAME", accountName);
		dataMap.put("SIGN_DATA", json.getString("ACCOUNT_ID")+"|"+NewAccountConstant.ASSET_TYPE+"|"+json.getString("CHANNEL_NO"));
		//获取接口地址
		String url=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.ZCZX_INTEGRAL_QUERY.getKey());;
		if (StringUtil.isNull(url)) {
			log.error(logMsg+"配置资产中心接口为空");
			resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
			return resultJson;
		}
		//调用资产中心
		try {
			JSONObject result = JSONObject.parseObject(DebAsetHttpUtil.sendPost(url,headerMap, dataMap,logMsg));
			if(AccountConstant.REPCD_SUCCESS.equals(result.getJSONObject("header").getString("repcd"))
					&&AccountConstant.RESULT_CODE_SUCCESS.equals(result.getJSONObject("data").getString("RESULT_CODE"))){
				log.info(logMsg+"资产中心处理成功");
				JSONObject resData=result.getJSONObject("data");
				resultJson.put("resultCode",NewAccountConstant.RETURN_CODE_SUCCESS);
				resultJson.put("BALANCE", resData.getString("ENABLE_NUMBER"));//可用余额
				resultJson.put("TOTAL_BALANCE", resData.getString("CURRENT_NUMBER"));//积分余额
				return resultJson;
			}else{
				log.info(logMsg+"资产中心处理失败："+result.getJSONObject("header").getString("repmsg"));
				resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
				return resultJson;
			}
		} catch (Exception e) {
			log.info(logMsg+"资产中心接口处理异常:"+e.getMessage());
			resultJson.put("resultCode", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("resultMsg", "资产中心接口异常");
			e.printStackTrace();
			return resultJson;
		}
	}

	/**
	 * 账户户号积分查询
	 * @param jsonObject
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject queryConsNoIntegral(JSONObject jsonObject) {
		String logMsg=jsonObject.getString("LOG_MSG");
		JSONObject resultJson=new JSONObject();
		String accountId=jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String token=jsonObject.getString("TOKEN");
		JSONObject returnJson = DebUserCentreUtil.queryConsNoList(accountId, token, logMsg);
		if(NewAccountConstant.RETURN_CODE_FAIL.equals(returnJson.getString("returnCode"))){
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", returnJson.getString("returnMsg"));
			return ResultModel.ReturnErrorJson(resultJson);
			
		}
		List<Map<String, Object>> powerUserList=(List<Map<String, Object>>) returnJson.get("consNoList");
		if(powerUserList==null||powerUserList.size()==0){
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
			resultJson.put("DESCRIBE", "无绑定户号");
			return ResultModel.ReturnSucceedJson(resultJson);
		}
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("accountId", accountId);
		params.put("list", powerUserList);
		List<Map<String, Object>> consNoList = consNoIntegralMapper.selectConsNoList(params);
		Map<String, Object> resMap=new HashMap<String, Object>();
		ProvinceCodeEnums[] enums = ProvinceCodeEnums.values();
		if(consNoList!=null&&consNoList.size()!=0){
			for (Map<String, Object> map : consNoList) {
				for (ProvinceCodeEnums ProvinceCodeEnum : enums) {
					if((map.get("PROVINCE_CODE").equals(ProvinceCodeEnum.getShortCode()))||(map.get("PROVINCE_CODE").equals(ProvinceCodeEnum.getLongCode()))) {
						map.put("PROVINCE_NAME", ProvinceCodeEnum.getMsg());
						map.put("PROVINCE_CODE", ProvinceCodeEnum.getLongCode());
					}
				}
				resMap.put(map.get("CONS_NO").toString(), "1");
			}
		}
		//需补充积分为0的户号
		if(resMap.size()!=powerUserList.size()){
			for (Map<String, Object> map : powerUserList) {
				if(resMap.get(map.get("POWER_USER_NO"))==null){
					Map<String, Object> res=new HashMap<String, Object>();
					res.put("CONS_NO", map.get("POWER_USER_NO"));
					res.put("PROVINCE_CODE", map.get("PROVINCE_CODE"));
					for (ProvinceCodeEnums ProvinceCodeEnum : enums) {
						if((res.get("PROVINCE_CODE").equals(ProvinceCodeEnum.getShortCode()))||(res.get("PROVINCE_CODE").equals(ProvinceCodeEnum.getLongCode()))) {
							res.put("PROVINCE_NAME", ProvinceCodeEnum.getMsg());
						}
					}
					res.put("TOTAL_BALANCE", BigDecimal.ZERO);
					res.put("CONSUME_BALANCE", BigDecimal.ZERO);
					consNoList.add(res);
				}
			}
		}
		
		resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
		resultJson.put("RESULT_LIST", consNoList);
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 户号明细查询
	 * @param jsonObject
	 * @return
	 */
	public JSONObject queryConsNoIntegralDetail(JSONObject jsonObject){
		JSONObject resultJson=new JSONObject();
		String accountId=jsonObject.getString("ACCOUNT_ID");//登录账户ID
		String consNo=jsonObject.getString("CONS_NO");//户号
		String pageIndex = jsonObject.getString("PAGE_INDEX");//页码
		String dealType = jsonObject.getString("AMT_DIRECTION");//业务方向
		//分页
		PageUtil pageUtil=new PageUtil();
		pageUtil.setPageIndex(Integer.parseInt(pageIndex));//设置页码
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("accountId", accountId);//账户ID
		params.put("consNo", consNo);//户号
		params.put("start", pageUtil.getStart());//分页起始位置
		params.put("end", pageUtil.getEnd());//分页结束位置
		params.put("dealType", dealType);//业务方向
		List<Map<String, Object>> consNoDetail = consNoIntegralMapper.selectConsNoDetail(params);
		if(consNoDetail!=null&&consNoDetail.size()!=0){
			for (Map<String, Object> map : consNoDetail) {
				if(NewAccountConstant.DEAL_TYPE_EXPEND.equals(map.get("AMT_DIRECTION").toString())){
					map.put("BUSS_DISCRIBLE", NewAccountConstant.BUSS_TYPE_MAP.get(map.get("BUSS_DISCRIBLE")));
				}
				map.put("CREATEE_TIME", map.get("CREATE_TIME").toString().replace(".0", ""));
			}
		}
		int totalCount = consNoIntegralMapper.selectConsNoDetailTotalCount(params);
		pageUtil.setTotalCount(totalCount);//设置总条数,get总页数
		resultJson.put("RECNUM", consNoDetail.size());//当前笔数
		resultJson.put("TOTRECNUM", totalCount);//总笔数
		resultJson.put("PAGCNT", pageUtil.getTotalPage());//总页数
		resultJson.put("RESULT_LIST", consNoDetail);
		return ResultModel.ReturnSucceedJson(resultJson);
	}
	
	/**
	 * 过期积分查询
	 * @param jsonObject
	 * @return
	 */
	public JSONObject queryStaleIntegral(JSONObject jsonObject){
		String logMsg=jsonObject.getString("LOG_MSG");
		JSONObject resultJson=new JSONObject();
		String staleDate=jsonObject.getString("STALE_DATE");//过期日期
		if(StringUtil.isNull(staleDate)){
			staleDate=TimeUtil.getNextMonthday();
		}
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("staleDate", staleDate);
		params.put("accountId", jsonObject.getString("ACCOUNT_ID"));
		BigDecimal staleIntegral=null;
		try {
			staleIntegral = incomeIntegralMapper.queryStaleIntegral(params);
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_SUCCESS);
			resultJson.put("STALE_INTEGRAL", staleIntegral==null?"0":staleIntegral.toString());
		} catch (Exception e) {
			log.info(logMsg+"查询数据库异常");
			resultJson.put("STATUS", NewAccountConstant.RETURN_CODE_FAIL);
			resultJson.put("DESCRIBE", "查询数据库异常");
			resultJson.put("STALE_INTEGRAL", "0");
			e.printStackTrace();
		}
		return ResultModel.ReturnSucceedJson(resultJson);
	}

	/**
	 * 老系统积分划转专用插入数据库接口
	 * @return
	 */
	public JSONObject changeInsertDb(JSONObject jsonObject){
		String accountId=jsonObject.getString("ACCOUNT_ID");//userid
		String accountName=jsonObject.getString("ACCOUNT_NAME");//username
		String consNo=jsonObject.getString("POWER_USER_NO");//户号
		String provinceCode=jsonObject.getString("PROVINCE_CODE");//省码
		String orgNo=jsonObject.getString("ORG_NO");//供电单位
		String powerId=jsonObject.getString("POWERID");//电力积分id
		String channelNo=jsonObject.getString("CHANNEL_NO");//收入来源渠道编码
		String serialNo=jsonObject.getString("BUSINESS_ID");//收入来源流水号,使用统一流水号
		BigDecimal balance=jsonObject.getBigDecimal("BALANCE");//收入总金额
		try {
			//直接获取绑定的户号信息
			JSONObject queryJson=new JSONObject();
			//{"CHANNEL_NO":"5","ACCOUNT_ID":"44f90082e9f74d979ab9bc2bd18c11a6","ACCOUNT_NAME":"王五"}
			queryJson.put("CHANNEL_NO",channelNo);
			queryJson.put("ACCOUNT_ID",accountId);
			queryJson.put("ACCOUNT_NAME",accountName);
			queryIntegral(queryJson);
			List<EcBpInComeIntegral> incomeIntegralList=new ArrayList<EcBpInComeIntegral>();//积分收入表List
			List<EcBpConsNoIntegral> consNoIntegralList=new ArrayList<EcBpConsNoIntegral>();//户号账户表List
			BigDecimal totalBalance=BigDecimal.ZERO;//本次转入的总转入积分
			totalBalance=totalBalance.add(balance);
			EcBpInComeIntegral incomeIntegral=new EcBpInComeIntegral();
			incomeIntegral.setIncomeId(UUIDUtil.getUUID());//收入ID
			incomeIntegral.setAccountId(accountId);//总账户ID
			incomeIntegral.setConsNo(consNo);//户号
			incomeIntegral.setProvinceCode(provinceCode);//省码
			incomeIntegral.setOrgNo(orgNo);//户号
			incomeIntegral.setPowerId(powerId);//电力积分id
			incomeIntegral.setIncomeChannel(channelNo);//收入来源渠道编码
			incomeIntegral.setSerialNo(serialNo);//收入来源流水号,使用统一流水号
			incomeIntegral.setIncomeSource(NewAccountConstant.BUSS_TYPE_DLJFZR);//业务类型,04：积分划转
			incomeIntegral.setIncomeType(NewAccountConstant.OPERATION_TYPE_ZD);//收入类型,01自动
			incomeIntegral.setSourceInstructions("电力积分转入");//来源说明/积分类型
			incomeIntegral.setSourceNumber(balance);//来源数量
			incomeIntegral.setIncomeBalance(balance);//收入总金额
			incomeIntegral.setUsableBalance(balance);//可用金额
			incomeIntegral.setChannelCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//渠道积分生成日期YYYYMMdd/交易时间
			incomeIntegral.setIncomeTime(TimeUtil.getDate( "YYYYMMdd"));//收入日期YYYYMMdd
			incomeIntegral.setStaleTime((Integer.parseInt(TimeUtil.getDate("YYYY"))+3)+"1231");//过期日期YYYYMMdd
			incomeIntegral.setStatus(NewAccountConstant.INCOME_INTEGRAL_STATUS_USABLE);//状态01:可用
			incomeIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			incomeIntegralList.add(incomeIntegral);

			EcBpConsNoIntegral consNoIntegral=new EcBpConsNoIntegral();//户号账户实体
			consNoIntegral.setConsNo(consNo);//户号
			consNoIntegral.setAccountId(accountId);//总账户ID
			consNoIntegral.setProvinceCode(provinceCode);//省码
			consNoIntegral.setCityCode(orgNo);//地市编码------------？？？？？？？？？？？
			consNoIntegral.setHsdwNo(orgNo);//核算单位编码-------------？？？？？？？？？？？
			consNoIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			consNoIntegral.setUpdateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//修改时间
			consNoIntegral.setBalance(balance);//积分余额
			for (int j = 0; j < consNoIntegralList.size(); j++) {
				EcBpConsNoIntegral ecBpConsNoIntegral = consNoIntegralList.get(j);
				if(consNo.equals(ecBpConsNoIntegral.getConsNo())){
					consNoIntegral.setBalance(consNoIntegral.getBalance().add(ecBpConsNoIntegral.getBalance()));
					consNoIntegralList.remove(j);//移除该条户号记录
				}
			}
			consNoIntegralList.add(consNoIntegral);
			EcBpAccountIntegralDetail accountIntegralDetail = new EcBpAccountIntegralDetail();
			String detailId=UUIDUtil.getUUID();//明细ID（UUID）返回报文中的业务ID
			//插入积分收入表
			int incomeNum=incomeIntegralMapper.insertList(incomeIntegralList);
			log.info("积分收入表插入成功,条数:"+incomeNum);
			//插入户号账户表
			int consNoNum=consNoIntegralMapper.batchInsertOrUpdate(consNoIntegralList);
			log.info("积分户号账户表插入或更新成功,条数:"+consNoNum);
			//插入 积分明细表
			accountIntegralDetail.setDetailId(detailId);//明细ID（UUID）
			accountIntegralDetail.setAccountId(accountId);//总账户ID
			accountIntegralDetail.setAccountName(accountName);//账户名称
			accountIntegralDetail.setSerialNo(serialNo);//收支流水号
			accountIntegralDetail.setDealType(NewAccountConstant.DEAL_TYPE_INCOME);//业务方向
			accountIntegralDetail.setBalance(totalBalance);//积分金额
			accountIntegralDetail.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			accountIntegralDetail.setDealTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//交易时间=创建时间
			accountIntegralDetail.setBussDiscrible("积分划转");//业务描述
			accountIntegralDetail.setBussType(NewAccountConstant.BUSS_TYPE_DLJFZR);//业务类型 04:积分划转
			accountIntegralDetail.setAcctDate(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//账务日期
			accountIntegralDetail.setChannelNo(channelNo);//渠道编码
			accountIntegralDetailMapper.insert(accountIntegralDetail);
			log.info("积分账户明细表插入成功,收支流水号:"+serialNo+",交易积分:"+totalBalance+",业务方向:"+NewAccountConstant.DEAL_TYPE_INCOME);
			//更新 积分账户总表
			EcBpAccountIntegral accountIntegral = accountIntegralMapper.selectIntegralByUnionId(accountId);
			accountIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
			accountIntegral.setBalance(accountIntegral.getBalance().add(totalBalance));//总可用积分
			accountIntegralMapper.update(accountIntegral);
			log.info("积分账户总表更新成功,总可用积分:"+accountIntegral.getBalance());
			return ResultModel.ReturnSucceedJson(accountIntegral);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ResultModel.ReturnErrorJson();
	}
	/**
	 * 新老系统都有积分数据的账户处理
	 * @param 
	 * @return
	 * @throws Exception 
	 */
	@Override
	public JSONObject selectAccountDbList(JSONObject jsonObject){
		JSONObject resultJson=new JSONObject();
		String logMsg=jsonObject.getString("LOG_MSG");
		JSONArray jsonArray = jsonObject.getJSONArray("ACCOUNT_ID_LIST");
		Map<String, Object> params=new HashMap<String, Object>();
		if(jsonArray!=null&&jsonArray.size()!=0){
			params.put("array", jsonArray.toArray());
		}
		List<EcBpAccountIntegral> accountDbList=accountIntegralMapper.selectAccountDbList(params);
		Map<String, String> resultMap=new HashMap<String, String>();
		for (EcBpAccountIntegral accountIntegral : accountDbList) {
			BigDecimal currentBalance=accountIntegral.getBalance();//处理前的积分
			String accountId=accountIntegral.getAccountId();
			//查询老系统所有积分收入明细
			List<EcBpMemberOld> oldIntegralList=null;
			try {
				oldIntegralList = memberMapper.selectOldIntegral(accountId);
			} catch (Exception e) {
				resultMap.put(accountId, "-1");
				log.info(logMsg+accountId+"老系统数据库查询失败");
				continue;
			}
			String bussId=UUIDUtil.getUUID();
			if(oldIntegralList==null||oldIntegralList.size()==0){
				resultMap.put(accountId, "0");
				log.info(logMsg+accountId+"老系统无积分");
				continue;
			}
			//转入新系统数据库
			try {
				oldDbListToNewDb(oldIntegralList, accountIntegral, "1", bussId,logMsg);
				String balance= (accountIntegral.getBalance().subtract(currentBalance)).toString();
				resultMap.put(accountId, balance);
				log.info(logMsg+accountId+"转入"+balance+"积分");
			} catch (Exception e) {
				resultMap.put(accountId, "-2");
				log.info(logMsg+accountId+"老系统无积分");
			}
		}
		resultJson.put("RESULT_MAP", resultMap);
		return ResultModel.ReturnSucceedJson(resultJson);
	}
	
	
	/**
	 * 新增账户/及新老系统都有积分数据的账户处理
	 * @param oldIntegralList
	 * @param accountIntegral
	 * @param channelNo
	 * @param bussId
	 * @param logMsg
	 * @return
	 * @throws Exception
	 */
	private EcBpAccountIntegral oldDbListToNewDb(List<EcBpMemberOld> oldIntegralList,
			EcBpAccountIntegral accountIntegral,String channelNo,String bussId,String logMsg) throws Exception{
		String accountId=accountIntegral.getAccountId();//总账户ID
		String accountName=accountIntegral.getAccountName();
		//不为空,则全部插入收入表
		List<EcBpInComeIntegral> incomeIntegralList=new ArrayList<EcBpInComeIntegral>();//积分收入表List
		List<EcBpConsNoIntegral> consNoIntegralList=new ArrayList<EcBpConsNoIntegral>();//户号账户表List
		List<EcBpFrozenLockRecord> FrozenLockList=new ArrayList<EcBpFrozenLockRecord>();//积分锁定冻结表List
		BigDecimal totalBalance=new BigDecimal("0");//本次转入的总可用积分
		BigDecimal totalFrozenBalance=new BigDecimal("0");//本次转入的总冻结积分
		String serialNo=StringUtil.isNull(bussId)?UUIDUtil.getUUID():bussId;//收入来源流水号,使用统一流水号
		for (EcBpMemberOld memberOld : oldIntegralList) {
			String createTime=TimeUtil.getDate("YYYYMMddHHmmssSSS");//创建时间
			BigDecimal balance=new BigDecimal(memberOld.getBpValueRemain());//可用积分
			String incomeId=UUIDUtil.getUUID();//收入ID,用于各表收入ID一致
			//积分收入表
			EcBpInComeIntegral incomeIntegral=new EcBpInComeIntegral();
			incomeIntegral.setIncomeId(incomeId);//收入ID
			incomeIntegral.setAccountId(accountIntegral.getAccountId());//总账户ID
			incomeIntegral.setConsNo(memberOld.getPowerUserNo());//户号
			incomeIntegral.setIncomeChannel(memberOld.getChannelIdCreate());//收入来源渠道编码
			incomeIntegral.setSerialNo(serialNo);//收入来源流水号,使用统一流水号
			incomeIntegral.setIncomeSource(NewAccountConstant.BUSS_TYPE_LXTJFZR);//收入来源,09：老系统积分转入
			incomeIntegral.setIncomeType(NewAccountConstant.OPERATION_TYPE_ZD);//收入类型,01自动
			incomeIntegral.setSourceInstructions(memberOld.getOriginRemark());//来源说明
			incomeIntegral.setSourceNumber(balance);//来源数量
			incomeIntegral.setIncomeBalance(balance);//收入总金额
			incomeIntegral.setUsableBalance(balance);//可用金额
			incomeIntegral.setChannelCreateTime(memberOld.getStartTime());//渠道积分生成日期
			incomeIntegral.setIncomeTime(TimeUtil.getDate("YYYYMMdd"));//收入日期
			incomeIntegral.setStaleTime(memberOld.getEndTime());//过期日期
			incomeIntegral.setStatus("1".equals(memberOld.getBpIsFrozen())?
					NewAccountConstant.INCOME_INTEGRAL_STATUS_FROZEN:NewAccountConstant.INCOME_INTEGRAL_STATUS_USABLE);//冻结状态
			incomeIntegral.setCreateTime(createTime);//创建时间
			incomeIntegralList.add(incomeIntegral);
			//户号账户表
			if(!StringUtil.isNull(memberOld.getPowerUserNo())){
				EcBpConsNoIntegral consNoIntegral=new EcBpConsNoIntegral();
				consNoIntegral.setConsNo(memberOld.getPowerUserNo());//户号
				consNoIntegral.setAccountId(accountId);//总账户ID
				consNoIntegral.setProvinceCode(memberOld.getProvinceId());//省码,可能为空
				consNoIntegral.setCreateTime(createTime);//创建时间
				if("1".equals(memberOld.getBpIsFrozen())){//被冻结
					consNoIntegral.setFrozenBalance(balance);//冻结积分
					consNoIntegral.setBalance(BigDecimal.ZERO);
				}else{
					consNoIntegral.setBalance(balance);//积分余额
					consNoIntegral.setFrozenBalance(BigDecimal.ZERO);
				}
				if(consNoIntegralList.size()!=0){
					for (int i = 0; i < consNoIntegralList.size(); i++) {
						EcBpConsNoIntegral consNoIntegra1=consNoIntegralList.get(i);
						if(consNoIntegra1.getConsNo().equals(consNoIntegral.getConsNo())){
							consNoIntegral.setBalance(consNoIntegra1.getBalance().add(consNoIntegral.getBalance()));//积分余额
							consNoIntegral.setFrozenBalance(consNoIntegra1.getFrozenBalance().add(consNoIntegral.getFrozenBalance()));//冻结积分
							consNoIntegralList.remove(i);
						}
					}
				}
				consNoIntegralList.add(consNoIntegral);
			}
			//积分冻结锁定表
			if("1".equals(memberOld.getBpIsFrozen())){
				EcBpFrozenLockRecord frozenLockRecord = new EcBpFrozenLockRecord();
				frozenLockRecord.setRecordId(UUIDUtil.getUUID());//记录ID
				frozenLockRecord.setBalance(balance);//积分
				frozenLockRecord.setIncomeId(incomeId);//收入ID
				frozenLockRecord.setFlType(NewAccountConstant.INTEGRAL_STATUS_FROZEN);//01锁定 02冻结
				frozenLockRecord.setFlReason("老系统积分转入");//原因
				frozenLockRecord.setOperationTime(createTime);//操作时间
				FrozenLockList.add(frozenLockRecord);
				totalFrozenBalance=totalFrozenBalance.add(balance);
			}else{
				//没有锁定,加入总积分
				totalBalance=totalBalance.add(balance);
			}
		}
		try {
			//插入积分收入表
			int incomeNum=incomeIntegralMapper.insertList(incomeIntegralList);
			log.info(logMsg+"积分收入表插入成功,老系统:"+incomeIntegralList.size()+",新系统:"+incomeNum);
			if(consNoIntegralList.size()!=0){
				//插入户号账户表
				int consNoNum=consNoIntegralMapper.batchInsertOrUpdate(consNoIntegralList);
				log.info(logMsg+"积分户号账户表插入成功,老系统:"+consNoIntegralList.size()+",新系统:"+consNoNum);
			}
			if(FrozenLockList.size()!=0){
				//插入积分冻结锁定记录表
				int frozenLockNum=frozenLockRecordMapper.insertList(FrozenLockList);
				log.info(logMsg+"积分冻结锁定记录表插入成功,老系统:"+FrozenLockList.size()+",新系统:"+frozenLockNum);
			}
			//插入 积分明细表（老系统转入的可用积分）
			EcBpAccountIntegralDetail accountIntegralDetail = new EcBpAccountIntegralDetail();
			accountIntegralDetail.setDetailId(UUIDUtil.getUUID());//明细ID（UUID）
			accountIntegralDetail.setAccountId(accountId);//总账户ID
			accountIntegralDetail.setAccountName(accountName);//账户名称
			accountIntegralDetail.setSerialNo(serialNo);//收支流水号
			accountIntegralDetail.setDealType(NewAccountConstant.DEAL_TYPE_INCOME);//业务方向
			accountIntegralDetail.setBalance(totalBalance);//积分金额
			accountIntegralDetail.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//创建时间
			accountIntegralDetail.setDealTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));//交易时间=创建时间
			accountIntegralDetail.setBussDiscrible("老系统积分转入");//业务描述
			accountIntegralDetail.setBussType(NewAccountConstant.BUSS_TYPE_LXTJFZR);//业务类型 09:老系统积分转入
			accountIntegralDetail.setAcctDate(TimeUtil.getDate("YYYYMMdd"));//账务日期
			accountIntegralDetail.setChannelNo(channelNo);//渠道编码
			accountIntegralDetailMapper.insert(accountIntegralDetail);
			log.info(logMsg+"积分账户明细表插入成功,收支流水号:"+serialNo+",交易积分:"+totalBalance+",业务方向:"+NewAccountConstant.DEAL_TYPE_INCOME);
			//新系统中插入 积分账户总表
			accountIntegral.setCreateTime(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
			accountIntegral.setBalance(accountIntegral.getBalance().add(totalBalance));//总可用积分
			accountIntegral.setFrozenBalance(accountIntegral.getFrozenBalance().add(totalFrozenBalance));//总冻结积分
			accountIntegralMapper.insertOrUpdate(accountIntegral);
			log.info(logMsg+"积分账户总表插入成功,本次转入可用积分:"+totalBalance+
					",总可用积分:"+accountIntegral.getBalance()+",本次转入冻结积分:"+totalFrozenBalance+
					",总冻结积分:"+accountIntegral.getFrozenBalance());
			//将老系统中被划转走的数据 的收支方向更改为2
			memberMapper.update(oldIntegralList);
			//异步调用资产中心同步积分变更记录
			JSONObject jsonJ=new JSONObject();
			jsonJ.put("ACCOUNT_ID", accountId);
			jsonJ.put("ACCOUNT_NAME", accountName);
			jsonJ.put("CHANNEL_NO", channelNo);
			jsonJ.put("BUSINESS_ID", serialNo);//流水号
			jsonJ.put("BUSS_TYPE", NewAccountConstant.BUSS_TYPE_LXTJFZR);//业务类型 09:老系统积分转入
			jsonJ.put("BUSS_DISCRIBLE", NewAccountConstant.BUSS_TYPE_MAP.get(NewAccountConstant.BUSS_TYPE_LXTJFZR));//业务类型 09:老系统积分转入
			jsonJ.put("ACCT_DATE", TimeUtil.getDate("YYYYMMdd"));//账务日期
			jsonJ.put("INTEGRAL", totalBalance);//收入积分
			JSONObject result = modifyIntegral(jsonJ,NewAccountConstant.DEAL_TYPE_INCOME,logMsg);
			accountIntegralDetail.setStatus(result.getString("resultCode"));//同步至资产中心状态（0:失败1:成功）
			accountIntegralDetailMapper.update(accountIntegralDetail);
			log.info(logMsg+"积分账户明细表更新成功,流水号:"+serialNo+",同步状态:"+result.getString("resultCode"));
			if(result.getString("resultCode").equals(NewAccountConstant.RETURN_CODE_FAIL)){
				accountIntegral.setBalance(BigDecimal.ZERO);
			}
			return accountIntegral;
		} catch (Exception e) {
			log.error(logMsg+"新系统数据库插入失败"+e.getMessage());
			throw new Exception();
		}
	}
	
	public static void main(String[] args) {
		System.out.println(TimeUtil.getDate("YYYYMMddHHmmssSSS"));
	}

}
